<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <el-tabs v-model="activeTab" class="settings-tabs">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <el-form :model="basicSettings" label-width="120px" class="settings-form">
            <el-form-item label="系统名称">
              <el-input v-model="basicSettings.systemName" placeholder="请输入系统名称" />
            </el-form-item>
            
            <el-form-item label="系统描述">
              <el-input
                v-model="basicSettings.systemDescription"
                type="textarea"
                :rows="3"
                placeholder="请输入系统描述"
              />
            </el-form-item>
            
            <el-form-item label="时区设置">
              <el-select v-model="basicSettings.timezone" placeholder="请选择时区">
                <el-option label="北京时间 (UTC+8)" value="Asia/Shanghai" />
                <el-option label="东京时间 (UTC+9)" value="Asia/Tokyo" />
                <el-option label="纽约时间 (UTC-5)" value="America/New_York" />
                <el-option label="伦敦时间 (UTC+0)" value="Europe/London" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="语言设置">
              <el-select v-model="basicSettings.language" placeholder="请选择语言">
                <el-option label="简体中文" value="zh-CN" />
                <el-option label="English" value="en-US" />
                <el-option label="日本語" value="ja-JP" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="主题模式">
              <el-radio-group v-model="basicSettings.theme">
                <el-radio label="light">浅色模式</el-radio>
                <el-radio label="dark">深色模式</el-radio>
                <el-radio label="auto">跟随系统</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 数据设置 -->
        <el-tab-pane label="数据设置" name="data">
          <el-form :model="dataSettings" label-width="120px" class="settings-form">
            <el-form-item label="数据刷新间隔">
              <el-select v-model="dataSettings.refreshInterval" placeholder="请选择刷新间隔">
                <el-option label="5秒" :value="5" />
                <el-option label="10秒" :value="10" />
                <el-option label="30秒" :value="30" />
                <el-option label="1分钟" :value="60" />
                <el-option label="5分钟" :value="300" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="数据保存天数">
              <el-input-number
                v-model="dataSettings.retentionDays"
                :min="1"
                :max="365"
                controls-position="right"
              />
            </el-form-item>
            
            <el-form-item label="自动备份">
              <el-switch v-model="dataSettings.autoBackup" />
            </el-form-item>
            
            <el-form-item label="备份频率" v-if="dataSettings.autoBackup">
              <el-select v-model="dataSettings.backupFrequency" placeholder="请选择备份频率">
                <el-option label="每天" value="daily" />
                <el-option label="每周" value="weekly" />
                <el-option label="每月" value="monthly" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="数据压缩">
              <el-switch v-model="dataSettings.compression" />
            </el-form-item>
            
            <el-form-item label="异常数据处理">
              <el-radio-group v-model="dataSettings.anomalyHandling">
                <el-radio label="ignore">忽略</el-radio>
                <el-radio label="flag">标记</el-radio>
                <el-radio label="remove">移除</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 传感器设置 -->
        <el-tab-pane label="传感器设置" name="sensor">
          <el-form :model="sensorSettings" label-width="120px" class="settings-form">
            <el-form-item label="温度单位">
              <el-radio-group v-model="sensorSettings.temperatureUnit">
                <el-radio label="celsius">摄氏度 (°C)</el-radio>
                <el-radio label="fahrenheit">华氏度 (°F)</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="气压单位">
              <el-radio-group v-model="sensorSettings.pressureUnit">
                <el-radio label="hpa">百帕 (hPa)</el-radio>
                <el-radio label="kpa">千帕 (kPa)</el-radio>
                <el-radio label="mmhg">毫米汞柱 (mmHg)</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="风速单位">
              <el-radio-group v-model="sensorSettings.windSpeedUnit">
                <el-radio label="ms">米/秒 (m/s)</el-radio>
                <el-radio label="kmh">千米/时 (km/h)</el-radio>
                <el-radio label="mph">英里/时 (mph)</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="传感器校准">
              <el-button type="primary" @click="calibrateSensors">开始校准</el-button>
            </el-form-item>
            
            <el-form-item label="传感器状态检查">
              <el-switch v-model="sensorSettings.statusCheck" />
            </el-form-item>
            
            <el-form-item label="检查间隔" v-if="sensorSettings.statusCheck">
              <el-select v-model="sensorSettings.checkInterval" placeholder="请选择检查间隔">
                <el-option label="1分钟" :value="1" />
                <el-option label="5分钟" :value="5" />
                <el-option label="10分钟" :value="10" />
                <el-option label="30分钟" :value="30" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 告警设置 -->
        <el-tab-pane label="告警设置" name="alert">
          <el-form :model="alertSettings" label-width="120px" class="settings-form">
            <el-form-item label="启用告警">
              <el-switch v-model="alertSettings.enabled" />
            </el-form-item>
            
            <div v-if="alertSettings.enabled">
              <el-form-item label="温度告警">
                <div class="alert-range">
                  <span>最低温度：</span>
                  <el-input-number
                    v-model="alertSettings.temperature.min"
                    :precision="1"
                    controls-position="right"
                    style="width: 120px; margin: 0 10px;"
                  />
                  <span>°C</span>
                  <span style="margin-left: 20px;">最高温度：</span>
                  <el-input-number
                    v-model="alertSettings.temperature.max"
                    :precision="1"
                    controls-position="right"
                    style="width: 120px; margin: 0 10px;"
                  />
                  <span>°C</span>
                </div>
              </el-form-item>
              
              <el-form-item label="湿度告警">
                <div class="alert-range">
                  <span>最低湿度：</span>
                  <el-input-number
                    v-model="alertSettings.humidity.min"
                    :min="0"
                    :max="100"
                    controls-position="right"
                    style="width: 120px; margin: 0 10px;"
                  />
                  <span>%</span>
                  <span style="margin-left: 20px;">最高湿度：</span>
                  <el-input-number
                    v-model="alertSettings.humidity.max"
                    :min="0"
                    :max="100"
                    controls-position="right"
                    style="width: 120px; margin: 0 10px;"
                  />
                  <span>%</span>
                </div>
              </el-form-item>
              
              <el-form-item label="告警方式">
                <el-checkbox-group v-model="alertSettings.methods">
                  <el-checkbox label="email">邮件通知</el-checkbox>
                  <el-checkbox label="sms">短信通知</el-checkbox>
                  <el-checkbox label="push">推送通知</el-checkbox>
                  <el-checkbox label="sound">声音告警</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              
              <el-form-item label="告警频率">
                <el-select v-model="alertSettings.frequency" placeholder="请选择告警频率">
                  <el-option label="立即" value="immediate" />
                  <el-option label="每5分钟" value="5min" />
                  <el-option label="每15分钟" value="15min" />
                  <el-option label="每小时" value="1hour" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
        </el-tab-pane>
        
        <!-- 网络设置 -->
        <el-tab-pane label="网络设置" name="network">
          <el-form :model="networkSettings" label-width="120px" class="settings-form">
            <el-form-item label="API地址">
              <el-input v-model="networkSettings.apiUrl" placeholder="请输入API地址" />
            </el-form-item>
            
            <el-form-item label="连接超时">
              <el-input-number
                v-model="networkSettings.timeout"
                :min="1000"
                :max="60000"
                :step="1000"
                controls-position="right"
              />
              <span style="margin-left: 10px;">毫秒</span>
            </el-form-item>
            
            <el-form-item label="重试次数">
              <el-input-number
                v-model="networkSettings.retryCount"
                :min="0"
                :max="10"
                controls-position="right"
              />
            </el-form-item>
            
            <el-form-item label="启用缓存">
              <el-switch v-model="networkSettings.cache" />
            </el-form-item>
            
            <el-form-item label="缓存时间" v-if="networkSettings.cache">
              <el-input-number
                v-model="networkSettings.cacheTime"
                :min="60"
                :max="3600"
                controls-position="right"
              />
              <span style="margin-left: 10px;">秒</span>
            </el-form-item>
            
            <el-form-item label="网络状态检查">
              <el-button type="primary" @click="checkNetworkStatus" :loading="networkChecking">
                检查网络状态
              </el-button>
            </el-form-item>
            
            <el-form-item v-if="networkStatus">
              <el-alert
                :title="networkStatus.title"
                :type="networkStatus.type"
                :description="networkStatus.description"
                show-icon
                :closable="false"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Check,
  RefreshLeft,
  Setting
} from '@element-plus/icons-vue'

// 响应式数据
const activeTab = ref('basic')
const saving = ref(false)
const networkChecking = ref(false)
const networkStatus = ref(null)

// 基本设置
const basicSettings = reactive({
  systemName: '气象站数据管理系统',
  systemDescription: '基于STM32的智能气象站数据采集与分析系统',
  timezone: 'Asia/Shanghai',
  language: 'zh-CN',
  theme: 'light'
})

// 数据设置
const dataSettings = reactive({
  refreshInterval: 30,
  retentionDays: 90,
  autoBackup: true,
  backupFrequency: 'daily',
  compression: true,
  anomalyHandling: 'flag'
})

// 传感器设置
const sensorSettings = reactive({
  temperatureUnit: 'celsius',
  pressureUnit: 'hpa',
  windSpeedUnit: 'ms',
  statusCheck: true,
  checkInterval: 5
})

// 告警设置
const alertSettings = reactive({
  enabled: true,
  temperature: {
    min: -10,
    max: 50
  },
  humidity: {
    min: 20,
    max: 80
  },
  methods: ['email', 'push'],
  frequency: '15min'
})

// 网络设置
const networkSettings = reactive({
  apiUrl: 'http://localhost:8080/api',
  timeout: 5000,
  retryCount: 3,
  cache: true,
  cacheTime: 300
})

// 方法
const saveSettings = async () => {
  saving.value = true
  try {
    // 模拟保存设置
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 保存到本地存储
    localStorage.setItem('basicSettings', JSON.stringify(basicSettings))
    localStorage.setItem('dataSettings', JSON.stringify(dataSettings))
    localStorage.setItem('sensorSettings', JSON.stringify(sensorSettings))
    localStorage.setItem('alertSettings', JSON.stringify(alertSettings))
    localStorage.setItem('networkSettings', JSON.stringify(networkSettings))
    
    ElMessage.success('设置保存成功')
  } catch (error) {
    ElMessage.error('设置保存失败')
  } finally {
    saving.value = false
  }
}

const resetSettings = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置所有设置吗？此操作不可撤销。',
      '重置设置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 重置设置
    Object.assign(basicSettings, {
      systemName: '气象站数据管理系统',
      systemDescription: '基于STM32的智能气象站数据采集与分析系统',
      timezone: 'Asia/Shanghai',
      language: 'zh-CN',
      theme: 'light'
    })
    
    Object.assign(dataSettings, {
      refreshInterval: 30,
      retentionDays: 90,
      autoBackup: true,
      backupFrequency: 'daily',
      compression: true,
      anomalyHandling: 'flag'
    })
    
    Object.assign(sensorSettings, {
      temperatureUnit: 'celsius',
      pressureUnit: 'hpa',
      windSpeedUnit: 'ms',
      statusCheck: true,
      checkInterval: 5
    })
    
    Object.assign(alertSettings, {
      enabled: true,
      temperature: { min: -10, max: 50 },
      humidity: { min: 20, max: 80 },
      methods: ['email', 'push'],
      frequency: '15min'
    })
    
    Object.assign(networkSettings, {
      apiUrl: 'http://localhost:8080/api',
      timeout: 5000,
      retryCount: 3,
      cache: true,
      cacheTime: 300
    })
    
    ElMessage.success('设置已重置')
  } catch {
    // 用户取消
  }
}

const calibrateSensors = () => {
  ElMessage.info('传感器校准功能开发中...')
}

const checkNetworkStatus = async () => {
  networkChecking.value = true
  try {
    // 模拟网络检查
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    networkStatus.value = {
      title: '网络连接正常',
      type: 'success',
      description: 'API服务器连接正常，延迟: 45ms'
    }
  } catch (error) {
    networkStatus.value = {
      title: '网络连接异常',
      type: 'error',
      description: '无法连接到API服务器，请检查网络设置'
    }
  } finally {
    networkChecking.value = false
  }
}

const loadSettings = () => {
  try {
    const savedBasicSettings = localStorage.getItem('basicSettings')
    if (savedBasicSettings) {
      Object.assign(basicSettings, JSON.parse(savedBasicSettings))
    }
    
    const savedDataSettings = localStorage.getItem('dataSettings')
    if (savedDataSettings) {
      Object.assign(dataSettings, JSON.parse(savedDataSettings))
    }
    
    const savedSensorSettings = localStorage.getItem('sensorSettings')
    if (savedSensorSettings) {
      Object.assign(sensorSettings, JSON.parse(savedSensorSettings))
    }
    
    const savedAlertSettings = localStorage.getItem('alertSettings')
    if (savedAlertSettings) {
      Object.assign(alertSettings, JSON.parse(savedAlertSettings))
    }
    
    const savedNetworkSettings = localStorage.getItem('networkSettings')
    if (savedNetworkSettings) {
      Object.assign(networkSettings, JSON.parse(savedNetworkSettings))
    }
  } catch (error) {
    console.error('加载设置失败:', error)
  }
}

// 生命周期
onMounted(() => {
  loadSettings()
})
</script>

<style lang="scss" scoped>
.settings-container {
  padding: 20px;
  
  .settings-card {
    max-width: 800px;
    margin: 0 auto;
    
    .settings-tabs {
      margin-top: 20px;
      
      .settings-form {
        padding: 20px 0;
        
        .alert-range {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          gap: 10px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .settings-container {
    padding: 10px;
    
    .settings-card {
      .settings-form {
        .alert-range {
          flex-direction: column;
          align-items: flex-start;
        }
      }
    }
  }
}
</style>